package system

import (
	"context"
	"fmt"
	"strconv"
	"time"

	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type EditMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	menuModel model.SysMenuModel
}

func NewEditMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EditMenuLogic {
	return &EditMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
	}
}

func (l *EditMenuLogic) EditMenu(req *types.EditMenuRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	err = auth.HasPermission(l.menuModel,l.ctx,"system:dept:edit")
	if err != nil {
		return nil,errorx.Unauthorized
	}
	
	authinfo,err := auth.GetAuth(l.ctx)
	if err != nil {
		return nil,err
	}

	roleIds,err := auth.GetRoleIds(l.ctx)
	if err != nil {
		return nil,err
	}
	if isAdmin,_ := auth.IsAdmin(l.ctx); !isAdmin {
		// 判断是否拥有本菜单的权限信息
		err = l.menuModel.ExistByMIdRIds(l.ctx,nil,req.MenuId,roleIds)
		if err != nil {
			return nil,errorx.Unauthorized
		}
	}

	menu,err := l.menuModel.FindOne(l.ctx,req.MenuId)
	if err != nil {
		return nil,err
	}
	err = editValue(menu,&req.Menu)
	if err != nil {
		return nil,err
	}
	fmt.Println(menu)
	menu.UpdateBy = authinfo.NickName
	menu.UpdateTime = time.Now().Unix()
	err = l.menuModel.Edit(l.ctx,nil,menu)
	return &types.CommonResponse{
		Status: 200,
		Msg: "修改成功",
	},err
}

func editValue(origin *model.SysMenu,now *types.Menu)error{
	if len(now.ParentId) > 0{
		parentId,err := strconv.Atoi(now.ParentId)
		if err != nil {
			return err
		} 
		(*origin).ParentId = int64(parentId)
	}
	if len(now.MenuName) > 0 {
		(*origin).MenuName = now.MenuName
	}
	
	if now.OrderNum <= 0 {
		(*origin).OrderNum = now.OrderNum
	}
	
	if len(now.Path) <= 0{
		(*origin).Path = now.Path	
	} 
	if len(now.Component) > 0{
		(*origin).Component.String = now.Component
		(*origin).Component.Valid = true
	} 
	if len(now.Query) > 0 {
		(*origin).Query.String = now.Query
		(*origin).Query.Valid = true
	}
	if len(now.MenuType) > 0 {
		(*origin).MenuType = now.MenuType
	}
	if len(now.Visible) > 0 {
		(*origin).Visible = now.Visible
	}
	if len(now.Status) > 0 {
		(*origin).Status = now.Status
	}
	if len(now.Perms) > 0 {
		(*origin).Perms.String = now.Perms
		(*origin).Perms.Valid = true
	}
	if len(now.Icon) > 0 {
		(*origin).Icon = now.Icon
	}
	return nil
}
